package com.hanggold.captcha.util;

import com.hanggold.captcha.font.FontStreamService;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

import static com.hanggold.captcha.util.RandomUtil.randomInt;

/**
 * 加载字体.
 *
 * @author <a href="mailto:free@hanggold.com">free</a>
 * @date 2021-09-30 12:59
 * @since 1.0.0
 **/
@Slf4j
public final class FontFamilyUtil {
    
    private static final FontFamilyUtil INSTANCE = new FontFamilyUtil();
    
    private static final List<FontStreamService> FONT_STREAM_SERVICES = new ArrayList<>();
    
    static {
        ServiceLoader<FontStreamService> fontStreamServices = ServiceLoader.load(FontStreamService.class);
        for (FontStreamService fontStreamService : fontStreamServices) {
            FONT_STREAM_SERVICES.add(fontStreamService);
        }
    }
    
    /**
     * 字体文件流.
     *
     * @return inputStream
     */
    public InputStream inputStream() {
        FontStreamService fontStreamService = FONT_STREAM_SERVICES.get(randomInt(FONT_STREAM_SERVICES.size()));
        log.debug("fontSteamService: {}", fontStreamService.getClass().getName());
        return fontStreamService.read();
        
    }
    
    /**
     * 字体实例.
     *
     * @return FontFamilyUtil
     */
    public static FontFamilyUtil getInstance() {
        return INSTANCE;
    }
    
}
